'''
模拟写一个有道词典
请输入要翻译的词语：elephant
翻译结果：大象
================================
请输入要翻译的词语：tiger
翻译结果：老虎

请求->响应->解析

请求
1.知道请求地址  https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule
2.请求方式      post，因为地址没有发生变化
3.如果是post：知道请求参数传递规则（cookie，useragent，Form Data字典）

响应
1.接收响应
request.get():返回响应对象  request.get.text():获取响应内容
2.获取响应对象

解析：
1.将数据从响应内容中解析出来
2.将数据打印或保存
'''

# data={
# i: 猴子
# from: AUTO
# to: AUTO
# smartresult: dict
# client: fanyideskweb
# salt: 16300771124741
# sign: c9f67f7958107919ffd4850dfc2b1c72
# lts: 1630077112474
# bv: 9cdf7cab68eaa00d641026cad92ce7e8
# doctype: json
# version: 2.1
# keyfrom: fanyi.web
# action: FY_BY_REALTlME
# }

import requests
import json
import time
import random
from hashlib import md5

class YdSpider:
    def __init__(self):
        self.url="https://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule"
        self.headers = {
            'Cookie':"OUTFOX_SEARCH_USER_ID=1437484006@10.169.0.102; JSESSIONID=aaamMIE3XVUSvgqrIhgUx; OUTFOX_SEARCH_USER_ID_NCOO=1522332942.927912; fanyi-ad-id=114757; fanyi-ad-closed=1; ___rl__test__cookies=1630077112470",
            'Referer':"https://fanyi.youdao.com/",
            'User-Agent':"""Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"""

        }
        self.word = input("请输入要翻译的单词：")

    def md5s(self,s):
        '''加密'''
        m =md5()
        m.update(s.encode())#修改字符集
        h = m.hexdigest()#加密
        return  h


    def get_ts_salt_sign(self):
        '''获取ts，salt，sign的值'''
        ts= str(int(time.time()*1000))
        salt = ts+str(random.randint(0,9))
        sign = self.md5s("fanyideskweb" + self.word + salt + "Y2FYu%TNSbMCxc3t2u^XT")
        return ts,salt,sign

    def attack_yd(self):
        ts,salt,sign = self.get_ts_salt_sign()
        data = {
            "i": self.word,
            "from": "AUTO",
            "to": "AUTO",
            "smartresult": "dict",
            "client": "fanyideskweb",
            "salt": salt,
            "sign": sign,
            "lts": ts,
            "bv": "9cdf7cab68eaa00d641026cad92ce7e8",
            "doctype": "json",
            "version": "2.1",
            "keyfrom": "fanyi.web",
            "action": "FY_BY_REALTlME"
        }
        html = requests.post(url=self.url,headers = self.headers,data= data).text
        #str：{"translateResult":[[{"tgt":"The tiger","src":"老虎"}]],"errorCode":0,"type":"zh-CHS2en","smartResult":{"entries":["","tiger\r\n"],"type":1}}
        html = json.loads(html) #把json数据类型的字符串转换成python数据类型
        print(html["translateResult"][0][0]["tgt"])

if __name__ == '__main__':
    spider = YdSpider()
    spider.attack_yd()